package org.study.article.dao;

import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BatchPreparedStatementSetter;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;
import org.study.article.model.ArticleRecord;

import java.sql.Date;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.List;

@Repository
public class ArticleDao {

    @Autowired
    JdbcTemplate template;

    public int insert(List<ArticleRecord> data){
        if(data==null || data.size()==0)return 0;
        String sql= "insert into article_record(path,create_time,create_user_id,content,title) values(?,?,?,?,?)";
        int[] ints = template.batchUpdate(sql, new BatchPreparedStatementSetter() {
            @Override
            public void setValues(PreparedStatement ps, int i) throws SQLException {
                ps.setString(1, data.get(i).getPath());
                ps.setDate(2, new Date(DateTime.now().getMillis()));
                ps.setInt(3, 1);
                ps.setString(4,data.get(i).getContent());
                ps.setString(5,data.get(i).getTitle());
            }
            @Override
            public int getBatchSize() {
                return data.size();
            }
        });
        int flag =0;
        for(int value : ints){
            if(value>0) flag++;
        }
        return flag;
    }

    public List<ArticleRecord> listAll(){
        return template.query("select * from article_record where `del` = 0 order by id desc",new BeanPropertyRowMapper<ArticleRecord>(ArticleRecord.class));
    }
    public ArticleRecord selectByPrimaryKey(Long id) {
        return template.queryForObject("select * from article_record where id="+id,new BeanPropertyRowMapper<ArticleRecord>(ArticleRecord.class));
    }
}
